<template>
  <div>
    <Header :userInfo="userDTO"></Header>
    <div>
      <!-- 面包屑导航 -->
      <div class="nav-wrap">
        <p class="nav-p-pc" style="margin-top:-25px;text-align:left;">
          <a href="/">首页</a>
          <span class="sharp-content">&gt;</span>
          <span class="nav-sec">账号设置</span>
        </p>
      </div>

      <div class="container">
        <el-tabs tab-position="left" style="height: 400px;">
          <!-- 基本设置 -->
          <el-tab-pane label="基本设置">
            <el-form label-width="80px" style="margin-top: 20px">
              <el-form-item label="头像">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  name="portrait"
                  :show-file-list="false"
                  accept="image/png, image/jpeg"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="portrait" :src="portrait" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  <div class="el-upload__tip" slot="tip">
                    只能上传jpg/png文件，且不超过1MB
                  </div>
                </el-upload>
              </el-form-item>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="昵称">
                    <el-input size="medium" v-model="nickname"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item>
                    <button
                      @click="updateUserInfo"
                      type="button"
                      class="weui-btn weui-btn_mini weui-btn_primary"
                      style="width:155px;height:45px;font-size:17px;"
                    >
                      更新信息
                    </button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <!-- 修改密码 -->
          <el-tab-pane label="修改密码">
            <el-form
              :model="passwordForm"
              status-icon
              :rules="rules"
              ref="passwordForm"
              label-width="80px"
              style="margin-top: 20px"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item label="当前密码" prop="password">
                    <el-input
                      v-model="passwordForm.password"
                      show-password
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input
                      v-model="passwordForm.newPassword"
                      show-password
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input
                      v-model="passwordForm.confirmPassword"
                      show-password
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item>
                    <button
                      @click="updatePassword"
                      type="button"
                      class="weui-btn weui-btn_mini weui-btn_primary"
                      style="width:155px;height:45px;font-size:17px;"
                    >
                      修改密码
                    </button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <Footer></Footer>
  </div>
</template>

<script>
import Header from './Header/Header' //顶部登录条
import Footer from './Footer/index' //顶部登录条

export default {
  name: 'Setting',
  components: {
    Header,
    Footer,
  },
  data() {
    var validatePassword = (rule, value, callback) => {
      if (this.passwordForm.confirmPassword !== '') {
        this.$refs.passwordForm.validateField('confirmPassword')
      }
      callback()
    }
    var validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 用户信息
      userDTO: null,

      // 头像
      portrait: '',

      // 头像上传地址
      uploadUrl: process.env.VUE_APP_API_BASE + '/avatarUpload',

      // 昵称
      nickname: '',

      // 修改密码表单
      passwordForm: {
        password: '',
        newPassword: '',
        confirmPassword: '',
      },

      // 修改密码表单验证规则
      rules: {
        password: [{ required: true, message: '请输入当前密码' }],
        newPassword: [
          { required: true, message: '请输入新密码' },
          { validator: validatePassword, trigger: 'blur' },
        ],
        confirmPassword: [
          { required: true, message: '请输入确认密码' },
          { validator: validateConfirmPassword, trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    // 检测本地储存中是否存在用户对象
    const user = localStorage.getItem('user')

    if (user != null) {
      this.userDTO = JSON.parse(user)
      this.nickname = this.userDTO.content.name
      this.portrait = this.userDTO.content.portrait
    }
  },
  methods: {

    // 头像上传成功处理
    handleAvatarSuccess(res, file) {
      // this.avatar = URL.createObjectURL(file.raw)
      this.portrait = res.filePath
      console.log(res)
    },

    // 上传前验证
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 1

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
      }
      // return isJPG && isLt2M
      return isLt2M
    },

    // 修改个人信息
    updateUserInfo() {
      const data = `userid=${this.userDTO.content.id}&portrait=${this.portrait}&name=${this.nickname}`
      return this.axios
        .post('user/updateUserInfo', data, {
          headers: {
            'content-type': 'application/x-www-form-urlencoded',
          },
        })
        .then(res => {
          if (res.data.success) {
            this.userDTO.content.name = this.nickname
            this.userDTO.content.portrait = this.portrait
            localStorage.setItem('user', JSON.stringify(this.userDTO))
            this.$message.success('更新成功！')
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch(err => {
          console.log(err)
          this.$message.error('更新失败！')
        })
    },

    // 修改密码
    updatePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          if (this.passwordForm.password !== this.userDTO.content.password) {
            this.$message.error('当前密码错误，修改密码失败！')
          } else {
            return this.axios
              .post(
                'user/updatePassword',
                `userid=${this.userDTO.content.id}&password=${this.passwordForm.newPassword}`,
                {
                  headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                  },
                }
              )
              .then(res => {
                if (res.data.success) {
                  this.userDTO.content.password = this.passwordForm.newPassword
                  localStorage.setItem('user', JSON.stringify(this.userDTO))
                  this.$refs.passwordForm.resetFields();
                  this.$message.success('修改密码成功！')
                } else {
                  this.$message.error(res.data.message)
                }
              })
              .catch(err => {
                console.log(err)
                this.$message.error('修改密码失败！')
              })
          }
        } else {
          return false
        }
      })
    },
  },
}
</script>

<style scoped>
.nav-wrap {
  padding-top: 40px;
  height: 50px;
  background: #fff;
}
.nav-p-pc {
  font-size: 16px;
  margin: 17px auto;
  vertical-align: top;
  width: 750px;
}
.nav-p-pc a:active,
.nav-p-pc a:link,
.nav-p-pc a:visited {
  color: #666;
}
.nav-p-pc .sharp-content {
  color: #666;
  margin-left: 5px;
}
.nav-p-pc .nav-sec {
  margin-left: 5px;
  color: #999;
}

.container {
  width: 750px;
  margin: 0 auto;
}

.avatar-uploader {
  text-align: left;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.weui-btn {
  position: relative;
  display: block;
  margin-left: auto;
  margin-right: auto;
  padding-left: 0.373rem;
  padding-right: 0.373rem;
  box-sizing: border-box;
  font-size: 0.48rem;
  text-align: center;
  text-decoration: none;
  color: #fff;
  line-height: 2.33333333;
  border-radius: 4px;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  overflow: hidden;
}
.weui-btn_primary {
  background-color: #00b38a;
}
.weui-btn_mini {
  display: inline-block;
  padding: 0 1.32em;
  line-height: 2.3;
  font-size: 0.347rem;
}
button.weui-btn,
input.weui-btn {
  width: 100%;
  border-width: 0;
  outline: 0;
  -webkit-appearance: none;
  cursor: pointer;
}
</style>
